/**
  ******************************************************************************
  * @file    app_acad.c
  * @author  Sherlock
  * @version V0.1
  * @date    07/31/2024
  * @brief   ACAD Handling
  ******************************************************************************
  * @copy
  *
  * <h2><center>&copy; COPYRIGHT 2010 Feirui</center></h2>
  */ 



/**
  * @brief  INCLUDE FILES.
  */
#ifndef	APP_GLOBALS_ACAD
#define	APP_GLOBALS_ACAD
#include <includes.h>
#include "acad_driver.h"
#include "acad_measure.h"
#include "acad_core.h"


static uint8_t ACAD_LocalRAMReset(void);
static uint8_t ACAD_GlobalRAMReset(void);

/**
  * @brief  State Control
  * @param  p_arg
  * @return none.
  * @Caller This is a task.
  * @Note   none.
  */
void App_Task_ACAD(void *p_arg)
{
  uint8_t  os_err, status = DEF_FALSE;
  OS_FLAGS os_value;
  
  (void)p_arg;
  
  
  /* RAM Reset */
  status |= ACAD_LocalRAMReset();
  status |= ACAD_GlobalRAMReset();
  
  /* HW Interface Initial */
  status |= ACAD_HWInit();

  /* Wait for Start action finish */
  // OSSemPend(App_Sem_STARTSYNC,0,&os_err);   //等待某个任务先进行并释放信号量，其它任务才能开始运行
  
  /* Wait for every task ready */
  OSTimeDlyHMSM(0, 0, 0, 100);

  /* HW start to work */
  status |= ACAD_HWEnable();

  /* Initial fault detection */
  if(status == DEF_FALSE)
    SYS_DebugERROR;

  /*  ACAD control flow */
 	while (DEF_TRUE)
	{
    /*  Wait for State Update output Flags  */
    os_value = OSFlagPend(App_Flags_ACAD,
                          OSACADFlags_ALL,
                          OS_FLAG_WAIT_SET_ANY + OS_FLAG_CONSUME,
                          0,
                          &os_err);
    if(os_err!=OS_ERR_NONE)
      SYS_DebugERROR;                                       /* Error- Only for Debug */

    /*  Workload running */
    status = DEF_FALSE;
    if(os_value & OSACADFlags_Measure)
    {
      status |= ACAD_MeasureHandle();
    }
    

    if(status)
      SetOSFlagsForNewInform(App_Flags_PID, OSPIDFlags_Output);     //发送PID输出标志
	}
}


static uint8_t ACAD_LocalRAMReset(void)
{
  ACTrace1stRecordFlag=DEF_FALSE;  //过零点标志位复位

  /* 滤波参数复位 */
  uint8_t i;
  for(i=0;i<ACFilterNL;i++) ChebyGensVoltV1LowpassXn[i]=0;
  for(i=0;i<ACFilterNL;i++) ChebyGensVoltV1LowpassYn[i]=0;
  for(i=0;i<ACFilterNL;i++) ChebyGensVoltV2LowpassXn[i]=0;
  for(i=0;i<ACFilterNL;i++) ChebyGensVoltV2LowpassYn[i]=0;
  for(i=0;i<ACFilterNL;i++) ChebyGensVoltV3LowpassXn[i]=0;
  for(i=0;i<ACFilterNL;i++) ChebyGensVoltV3LowpassYn[i]=0;

  // for(i=0;i<ACFilterNL;i++) ChebyGensCurrV1LowpassXn[i]=0;
  // for(i=0;i<ACFilterNL;i++) ChebyGensCurrV1LowpassYn[i]=0;
  // for(i=0;i<ACFilterNL;i++) ChebyGensCurrV2LowpassXn[i]=0;
  // for(i=0;i<ACFilterNL;i++) ChebyGensCurrV2LowpassYn[i]=0;
  // for(i=0;i<ACFilterNL;i++) ChebyGensCurrV3LowpassXn[i]=0;
  // for(i=0;i<ACFilterNL;i++) ChebyGensCurrV3LowpassYn[i]=0;

  for(i=0;i<ACFilterNL;i++) ChebyLoadVoltV1LowpassXn[i]=0;
  for(i=0;i<ACFilterNL;i++) ChebyLoadVoltV1LowpassYn[i]=0;
  for(i=0;i<ACFilterNL;i++) ChebyLoadVoltV2LowpassXn[i]=0;
  for(i=0;i<ACFilterNL;i++) ChebyLoadVoltV2LowpassYn[i]=0;
  for(i=0;i<ACFilterNL;i++) ChebyLoadVoltV3LowpassXn[i]=0;
  for(i=0;i<ACFilterNL;i++) ChebyLoadVoltV3LowpassYn[i]=0;

  for(i=0;i<ACFilterNL;i++) ChebyBuildVoltBEFLowpassXn[i]=0;
  for(i=0;i<ACFilterNL;i++) ChebyBuildVoltBEFLowpassYn[i]=0;

  /* 过零点检测参数复位 */
  GensUTraceRecordNum=0;  //被测电机
  GensUTraceRecordSta=0;
  GensUTraceP0Counter=0;
  GensUTraceLVCounter=0;
  GensUTraceLVStatus =0;
  // CurrUTraceRecordNum=0;  //被测电机电流
  // CurrUTraceRecordSta=0;
  // CurrUTraceP0Counter=0;
  // CurrUTraceLVCounter=0;
  // CurrUTraceLVStatus =0;
  LoadUTraceRecordNum=0;  //负载电机
  LoadUTraceRecordSta=0;
  LoadUTraceP0Counter=0;
  LoadUTraceLVCounter=0;
  LoadUTraceLVStatus =0;

  GensVTraceRecordNum=0;  //被测电机
  GensVTraceRecordSta=0;
  GensVTraceP0Counter=0;
  GensVTraceLVCounter=0;
  GensVTraceLVStatus =0;
  // CurrVTraceRecordNum=0;  //被测电机电流
  // CurrVTraceRecordSta=0;
  // CurrVTraceP0Counter=0;
  // CurrVTraceLVCounter=0;
  // CurrVTraceLVStatus =0;
  LoadVTraceRecordNum=0;  //负载电机
  LoadVTraceRecordSta=0;
  LoadVTraceP0Counter=0;
  LoadVTraceLVCounter=0;
  LoadVTraceLVStatus =0;

  GensWTraceRecordNum=0;  //被测电机
  GensWTraceRecordSta=0;
  GensWTraceP0Counter=0;
  GensWTraceLVCounter=0;
  GensWTraceLVStatus =0;
  // CurrWTraceRecordNum=0;  //被测电机电流
  // CurrWTraceRecordSta=0;
  // CurrWTraceP0Counter=0;
  // CurrWTraceLVCounter=0;
  // CurrWTraceLVStatus =0;
  LoadWTraceRecordNum=0;  //负载电机
  LoadWTraceRecordSta=0;
  LoadWTraceP0Counter=0;
  LoadWTraceLVCounter=0;
  LoadWTraceLVStatus =0;

  BuildVoltBEFTraceRecordNum=0;  //建磁电压
  BuildVoltBEFTraceRecordSta=0;
  BuildVoltBEFTraceP0Counter=0;
  BuildVoltBEFTraceLVCounter=0;
  BuildVoltBEFTraceLVStatus =0;

  /* 弱信号检测参数复位 */
  RecordGensUTraceMax=0;  //被测电机
  RecordGensVTraceMax=0;
  RecordGensWTraceMax=0;
  // RecordCurrUTraceMax=0;  //被测电机电流
  // RecordCurrVTraceMax=0;
  // RecordCurrWTraceMax=0;
  RecordLoadUTraceMax=0;  //负载电机
  RecordLoadVTraceMax=0;
  RecordLoadWTraceMax=0;
  RecordBuildVoltBEFTraceMax=0;  //建磁电压
  
  RecordGensUTraceMin=0;  //被测电机
  RecordGensVTraceMin=0;
  RecordGensWTraceMin=0;
  // RecordCurrUTraceMin=0;  //被测电机电流
  // RecordCurrVTraceMin=0;
  // RecordCurrWTraceMin=0;
  RecordLoadUTraceMin=0;  //负载电机
  RecordLoadVTraceMin=0;
  RecordLoadWTraceMin=0;
  RecordBuildVoltBEFTraceMin=0;  //建磁电压
  
  GensUTraceDCLimitUpper = ACVoltTraceDCValLower;  //被测电机
  GensVTraceDCLimitUpper = ACVoltTraceDCValLower;
  GensWTraceDCLimitUpper = ACVoltTraceDCValLower;
  // CurrUTraceDCLimitUpper = ACVoltTraceDCValLower;  //被测电机电流
  // CurrVTraceDCLimitUpper = ACVoltTraceDCValLower;
  // CurrWTraceDCLimitUpper = ACVoltTraceDCValLower;
  LoadUTraceDCLimitUpper = ACVoltTraceDCValLower;  //负载电机
  LoadVTraceDCLimitUpper = ACVoltTraceDCValLower;
  LoadWTraceDCLimitUpper = ACVoltTraceDCValLower;
  BuildVoltBEFTraceDCLimitUpper = ACVoltTraceDCValLower;  //建磁电压

  GensUTraceDCLimitLower = -ACVoltTraceDCValLower;  //被测电机
  GensVTraceDCLimitLower = -ACVoltTraceDCValLower;
  GensWTraceDCLimitLower = -ACVoltTraceDCValLower;
  // CurrUTraceDCLimitLower = -ACVoltTraceDCValLower;  //被测电机电流
  // CurrVTraceDCLimitLower = -ACVoltTraceDCValLower;
  // CurrWTraceDCLimitLower = -ACVoltTraceDCValLower;
  LoadUTraceDCLimitLower = -ACVoltTraceDCValLower;  //负载电机
  LoadVTraceDCLimitLower = -ACVoltTraceDCValLower;
  LoadWTraceDCLimitLower = -ACVoltTraceDCValLower;
  BuildVoltBEFTraceDCLimitLower = -ACVoltTraceDCValLower;  //建磁电压

  /* 标志位复位 */
  ACMeasureBufferAreaNum = 0;  //当前缓冲区指向0

  for(uint8_t i=0; i<ACADRecdataQNum; i++)   //清空缓冲区
		ACRXdataTempBuffer[i].InputType = ADCRecDataType_Null;
  
  /* 励磁历史记忆值清零 */
  ADCLastValue_GenExciteVolt = 0;
  ADCLastValue_GenExciteCurr = 0;
  ADCLastValue_LoadExciteVolt = 0;
  ADCLastValue_LoadExciteCurr = 0;
  
  /* 功率数据中位值滤波初始化 */
  // Comm_MediumFilterInitStructure(&MemGenPowerP1);
  // Comm_MediumFilterInitStructure(&MemGenPowerP2);
  // Comm_MediumFilterInitStructure(&MemGenPowerP3);
  // Comm_MediumFilterInitStructure(&MemGenPowerQ1);
  // Comm_MediumFilterInitStructure(&MemGenPowerQ2);
  // Comm_MediumFilterInitStructure(&MemGenPowerQ3);
  // Comm_MediumFilterInitStructure(&MemGenPowerS1);
  // Comm_MediumFilterInitStructure(&MemGenPowerS2);
  // Comm_MediumFilterInitStructure(&MemGenPowerS3);
  MemGenPowerP1 = 0;
  MemGenPowerP2 = 0;
  MemGenPowerP3 = 0;
  MemGenPowerQ1 = 0;
  MemGenPowerQ2 = 0;
  MemGenPowerQ3 = 0;
  MemGenPowerS1 = 0;
  MemGenPowerS2 = 0;
  MemGenPowerS3 = 0;
  MemGenPFL1 = 0;
  MemGenPFL2 = 0;
  MemGenPFL3 = 0;

  return DEF_TRUE;
}


static uint8_t ACAD_GlobalRAMReset(void)
{
  /* 全局数据清零 */
  FillGeneratorDataIntoRTMemory(&ACAD_RTGlobalData.GenVoltData, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  FillGeneratorDataIntoRTMemory(&ACAD_RTGlobalData.LoadVoltData, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
	FillExcitationDataIntoRTMemory(&ACAD_RTGlobalData.GenExcitationData, 0, 0);
	FillExcitationDataIntoRTMemory(&ACAD_RTGlobalData.LoadExcitationData, 0, 0);
	FillSynchronousDataIntoRTMemory(&ACAD_RTGlobalData.SyncData, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  FillPowerDataIntoRTMemory(&ACAD_RTGlobalData.PowerData, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
	FillBuildVoltDataIntoRTMemory(&ACAD_RTGlobalData.BuildVoltData, 0, 0, 0);

  return DEF_TRUE;
}


/**
  * @brief  TX DMA IRQ
  * @param  None
  * @retval None
  */
void DMA1_Channel1_IRQHandler(void)
{
  OS_CPU_SR  cpu_sr;
  
  OS_ENTER_CRITICAL();  /* Tell uC/OS-II that we are starting an ISR  进入临界段代码的宏        */
  OSIntEnter();         /* 中断进入服务函数，判断UCOS是否正常运行，以及中断嵌套级数，最多允许250级 */
	OS_EXIT_CRITICAL();   /* 退出临界段代码的宏 */

#if 1
	if((ACAD_DMA->INTSTS & ((uint32_t)0x00000002))!= 0)
  {
    ADC1->CTRL2 &= ((uint32_t)0xFFFFFFFE);					//关 ADC1
	  ACAD_DMA_Channel->CHCFG &= ((uint32_t)0xFFFFFFFE);		//关 DMA1_channel1
		uint8_t LastBufferAreaNum = ACMeasureBufferAreaNum;
	  ACMeasureBufferAreaNum = (ACMeasureBufferAreaNum + 1) % ADCBufferAreaNum; //指向下一个转换的缓冲区
    ACAD_DMA_Channel->MADDR = ACBufferArea1Address[ACMeasureBufferAreaNum];	//更换下一个缓存块用于保存AD转换结果
    ACAD_DMA_Channel->TXNUM = ACAD_DMA_BufferSize;		//每个缓存块有30个单元
    ACAD_DMA->INTCLR |= ((uint32_t)0x00000001);					//清除 DMA1_channel1中断标志
    ACAD_DMA_Channel->CHCFG |= ((uint32_t)0x00000001);		//开 DMA1_channel1
    ADC1->CTRL2 |= ((uint32_t)0x00000001);					//开 ADC1

    /* Post OSQ AC Receiver Data */
		for(uint8_t i=0; i<ACADRecdataQNum; i++)
		{
			if(ACRXdataTempBuffer[i].InputType==ADCRecDataType_Null)
			{
				ACRXdataTempBuffer[i].InputType=ADCRecDataType_Full;	//设置数据已经准备OK的标志
				ACRXdataTempBuffer[i].RawData=LastBufferAreaNum; //指向刚采集完的数据缓存块
				
				if(OSQPostOpt(App_Q_ACAD,&ACRXdataTempBuffer[i],OS_POST_OPT_NONE)!=OS_ERR_NONE)	//发送数据准备OK的事件（ACRXRawdatapoint=指定准备好的数据在哪个缓存块）
					SYS_DebugERROR;                         /* Error- Only for Debug */
				break;
			}
    }

    SetOSFlagsForNewInform(App_Flags_ACAD,OSACADFlags_Measure);     //发送测量标志
  }
#endif
#if 0
  if(DMA_GetIntStatus(ACAD_DMA_IT_Mode, ACAD_DMA))
  {
		uint8_t LastBufferAreaNum = ACMeasureBufferAreaNum;
	  ACMeasureBufferAreaNum = (ACMeasureBufferAreaNum + 1) % ADCBufferAreaNum; //指向下一个转换的缓冲区
	  ADC_Enable(ADC1, DISABLE);  //关 ADC
		DMA_EnableChannel(ACAD_DMA_Channel, DISABLE);  //关 DMA_channel1
    DMA_ConfigInt
		ACADCDMAInitStructure.MemAddr = ACBufferArea1Address[ACMeasureBufferAreaNum];  //更换下一个缓存块用于保存AD转换结果
		ACADCDMAInitStructure.BufSize = ACAD_DMA_BufferSize;  //每个缓存块有700个单元
		DMA_Init(ACAD_DMA_Channel, &ACADCDMAInitStructure);
		DMA_ClrIntPendingBit(ACAD_DMA_IT_Mode, ACAD_DMA);
		DMA_EnableChannel(ACAD_DMA_Channel, ENABLE);  //开 DMA_channel1
		ADC_Enable(ADC1, ENABLE);  //开 ADC
    
    /* Post OSQ AC Receiver Data */
		for(uint8_t i=0;i<ACRXdataBufferNum;i++)
		{
			if(ACRXdataTempBuffer[i].InputType==ADCRecDataType_Null)
			{
				ACRXdataTempBuffer[i].InputType=ADCRecDataType_Full;	//设置数据已经准备OK的标志
				ACRXdataTempBuffer[i].RawData=LastBufferAreaNum; //指向刚采集完的数据缓存块
				
				if(OSQPostOpt(App_Q_ACAD,&ACRXdataTempBuffer[i],OS_POST_OPT_NONE)!=OS_ERR_NONE)	//发送数据准备OK的事件（ACRXRawdatapoint=指定准备好的数据在哪个缓存块）
					SYS_DebugERROR;                         /* Error- Only for Debug */
				break;
			}
    }

    SetOSFlagsForNewInform(App_Flags_ACAD,OSACADFlags_Measure);     //发送测量标志
  }
#endif
  
  OSIntExit();                                 /* Tell uC/OS-II that we are leaving the ISR          */
}


#endif	/*	APP_GLOBALS_ACAD	*/

/******************* (C) COPYRIGHT 2010 Feirui *****END OF FILE****/
